package com.tarena.tocketmq.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class HelloController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/send")
    public String sendMsg(String name) {
        //1.封装一个消息对象
        Message<String> message = MessageBuilder.withPayload(name).build();
        //2.调用rocketMQTemplate发送消息
        //同步消息
//        SendResult result = rocketMQTemplate.syncSend("topic01", message);
//        return "同步消息发送成功";
        //同步延迟消息
//        SendResult result = rocketMQTemplate.syncSend("topic01", message, 3000, 3);
//        return "同步延迟消息发送成功";
        //异步消息
        rocketMQTemplate.asyncSend("topic01", message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("异步消息发送成功");
            }
            @Override
            public void onException(Throwable throwable) {
                log.error("异步消息发送失败");
            }
        });
        log.info("异步消息发送完毕");
        return "ok";
        //异步延迟消息
//        rocketMQTemplate.asyncSend("topic01", message, new SendCallback() {
//            @Override
//            public void onSuccess(SendResult sendResult) {
//                log.info("异步延迟消息发送成功");
//            }
//
//            @Override
//            public void onException(Throwable throwable) {
//                log.error("异步延迟消息发送失败");
//            }
//        }, 3000, 3);
//        log.info("异步延迟消息发送完毕");
//        return "ok";
    }
}
